#!/usr/local/bin/bash

#############################################################################
#      Redistribution and use in source and binary forms, with or without
#      modification, are permitted provided that the following conditions are
#      met:
#      
#      * Redistributions of source code must retain the above copyright
#        notice, this list of conditions and the following disclaimer.
#      * Redistributions in binary form must reproduce the above
#        copyright notice, this list of conditions and the following disclaimer
#        in the documentation and/or other materials provided with the
#        distribution.
#      * Neither the name of the  nor the names of its
#        contributors may be used to endorse or promote products derived from
#        this software without specific prior written permission.
#      
#      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#      "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#      LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#      A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#      OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#      SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#      LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#      DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#      THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#      (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#      OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#      Author: Andrew Sinitsyn aka boombick < boombick@gmail.com >
#
############################################################################

usage()
{
    echo "`basename $0`: String for search missing" 2>&1
    exit 1
}


if [ "$1" = "" ] ; then
	usage
	exit 1
fi

SEARCH=$@
GREEN=`echo -e '\033[0m\033[1;32m'`
YELLOW=`echo -e '\033[41m\033[1;33m'`
TMPFILE=/tmp/`whoami`-greplist

grep -srni "$SEARCH" . | \
grep -vE '(svn|jquery)' > $TMPFILE
 
awk -F: '\
BEGIN { curfile = 0; files = 0; strings = 0} \
{\
if ($1 != curfile) {\
	curfile = $1;
	printf "\n\033[1;36m%-30s\033[0m \n", $1; \
	files++; \
} \
	gsub(/^[ \t]+/, "", $3)
	printf "\033[1;31m%10s:\033[0m \033[1;32m%-80s\033[0m \n", $2, $3; \
	strings++;
} \
END { \
if (strings != 0) \
	print "-----\nFound \033[1m"strings"\033[0m matches in \033[1m"files"\033[0m file(s)"; \
else \
	print "Nothing found"
} \
' $TMPFILE | \
sed "s/$SEARCH/$YELLOW$SEARCH$GREEN/Ig"

rm $TMPFILE
